package com.quectel.core.module.dept.service.impl;


import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.dept.dao.DeptPersonRoleDao;
import com.quectel.core.module.dept.dto.DeptPersonAccessResourceDto;
import com.quectel.core.module.dept.dto.DeptPersonRoleDto;
import com.quectel.core.module.dept.dto.DeptPersonRoleRelationDto;
import com.quectel.core.module.dept.dto.DeptPersonRoleResourceDto;
import com.quectel.core.module.dept.entity.DeptPersonRoleEntity;
import com.quectel.core.module.dept.service.DeptPersonAccessResourceService;
import com.quectel.core.module.dept.service.DeptPersonRoleRelationService;
import com.quectel.core.module.dept.service.DeptPersonRoleResourceService;
import com.quectel.core.module.dept.service.DeptPersonRoleService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/07/27 10:30
 */
@DubboService
public class DeptPersonRoleServiceImpl implements DeptPersonRoleService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeptPersonRoleServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> DEPT_PERSON_ROLE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "DEPT_PERSON_ROLE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<DeptPersonRoleDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(DEPT_PERSON_ROLE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private DeptPersonRoleDao deptPersonRoleDao;
    @Autowired
    private DeptPersonAccessResourceService deptPersonAccessResourceService;
    @Autowired
    private DeptPersonRoleResourceService deptPersonRoleResourceService;
    @Autowired
    private DeptPersonRoleRelationService deptPersonRoleRelationService;

    @Override
    public List<DeptPersonRoleDto> selectRoleByPersonId(Long personId) {
        List<DeptPersonRoleDto> deptPersonRoleDtos = new ArrayList<>();
        List<DeptPersonRoleRelationDto> deptPersonRoleRelationDtos = deptPersonRoleRelationService.selectByPersonId(personId);
        if (CollectionUtils.isNotEmpty(deptPersonRoleRelationDtos)) {
            for (DeptPersonRoleRelationDto deptPersonRoleRelationDto : deptPersonRoleRelationDtos) {
                DeptPersonRoleEntity deptPersonRoleEntity = deptPersonRoleDao.selectById(deptPersonRoleRelationDto.getDeptRoleId());
                deptPersonRoleDtos.add(CopyUtils.copyObj(deptPersonRoleEntity, DeptPersonRoleDto.class));
            }
        }
        return deptPersonRoleDtos;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleMenuRelation(DeptPersonRoleDto dto) {
        //第一步先清除关系
        deptPersonRoleResourceService.deleteByRoleId(dto.getId());
        if (CollectionUtils.isEmpty(dto.getDeptPersonAccessResourceDtos())) {
            return;
        }

        //批量保存
        for (DeptPersonAccessResourceDto deptPersonAccessResourceDto : dto.getDeptPersonAccessResourceDtos()) {
            DeptPersonRoleResourceDto roleResourceDto = new DeptPersonRoleResourceDto();
            roleResourceDto.setDeptPersonRoleId(dto.getId());
            roleResourceDto.setAccessResourceId(deptPersonAccessResourceDto.getId());
            deptPersonRoleResourceService.save(roleResourceDto);
        }
    }


    @Override
    public DeptPersonRoleDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                DEPT_PERSON_ROLE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public DeptPersonRoleDto selectById(Long id) {
        DeptPersonRoleEntity entity = deptPersonRoleDao.selectById(id);
        DeptPersonRoleDto deptPersonRoleDto = paddingField(CopyUtils.copyObj(entity, DeptPersonRoleDto.class));

        if (deptPersonRoleDto != null) {
            //填充resource
            List<DeptPersonAccessResourceDto> deptPersonAccessResourceDtos = new ArrayList<>();
            List<DeptPersonRoleResourceDto> deptPersonRoleResourceDtos = deptPersonRoleResourceService.selectByRoleId(id);
            if (CollectionUtils.isNotEmpty(deptPersonRoleResourceDtos)) {
                for (DeptPersonRoleResourceDto deptPersonRoleResourceDto : deptPersonRoleResourceDtos) {
                    deptPersonAccessResourceDtos.add(deptPersonAccessResourceService.selectById(deptPersonRoleResourceDto.getAccessResourceId()));
                }

            }
            deptPersonRoleDto.setDeptPersonAccessResourceDtos(deptPersonAccessResourceDtos);
        }

        return deptPersonRoleDto;
    }

    @Override
    public List<DeptPersonRoleDto> queryList(Map<String, Object> params) {
        List<DeptPersonRoleEntity> list = deptPersonRoleDao.queryList(params);
        List<DeptPersonRoleDto> result = CopyUtils.copyList(list, DeptPersonRoleDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属社区等
     *
     * @param dto
     * @return
     */
    private DeptPersonRoleDto paddingField(DeptPersonRoleDto dto) {
        if (dto != null) {

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return deptPersonRoleDao.queryTotal(params);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long save(DeptPersonRoleDto dto) {
        DeptPersonRoleEntity entity = CopyUtils.copyObj(dto, DeptPersonRoleEntity.class);
        entity.setId(Snowflake.nextId());
        deptPersonRoleDao.insert(entity);

        dto.setId(entity.getId());
        saveRoleMenuRelation(dto);

        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(DeptPersonRoleDto dto) {
        DeptPersonRoleEntity entity = CopyUtils.copyObj(dto, DeptPersonRoleEntity.class);
        deptPersonRoleDao.updateById(entity);

        saveRoleMenuRelation(dto);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAllColumnById(DeptPersonRoleDto dto) {
        DeptPersonRoleEntity entity = CopyUtils.copyObj(dto, DeptPersonRoleEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, deptPersonRoleDao);

        saveRoleMenuRelation(dto);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        deptPersonRoleDao.deleteById(id);

        deptPersonRoleResourceService.deleteByRoleId(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
